package com.dongdong.zhuangji.config;
import com.dongdong.zhuangji.utils.StringToDateConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.util.pattern.PathPatternParser;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 *
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    // 重命名 Bean
    public StringToDateConverter customStringToDateConverter() {
        return new StringToDateConverter();
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(String.class, Date.class, source -> {
            if (source == null || source.isEmpty()) {
                return null;
            }

            // 定义支持的日期格式
            String[] formats = {
                    "yyyy-MM-dd HH:mm:ss",
                    "EEE MMM dd yyyy HH:mm:ss 'GMT'Z (中国标准时间)", // 匹配 Sun Jun 01 2025 00:00:00 GMT+0800 (中国标准时间)
                    "EEE MMM dd yyyy HH:mm:ss zzz", // 匹配 Sun Jun 01 2025 00:00:00 GMT+0800
                    "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" // 匹配 ISO 格式
            };

            for (String format : formats) {
                try {
                    return new SimpleDateFormat(format, Locale.US).parse(source);
                } catch (ParseException e) {
                    // 尝试下一个格式
                }
            }

            throw new IllegalArgumentException("Invalid date format: " + source);
        });
    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
    }

    /*@Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/{path:^(?!.*\\.js|\\.css|\\.html|\\.png|\\.jpg|\\.svg|\\.ico).*$}")
                .setViewName("forward:/index.html");
        registry.addViewController("/")
                .setViewName("forward:/index.html");
    }*/

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setPatternParser(new PathPatternParser());
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://192.168.1.245:5173,http://localhost:5173,http://haike.nat300.top/,http://dongdong.cloud/,http://www.dongdong.cloud/")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}